package com.fingard.dsp.bank.directbank.icbc02;

import java.util.concurrent.atomic.AtomicInteger;

import com.fingard.dsp.bank.directbank.bankInterface.IBalance;
import com.fingard.dsp.bank.reqrespobj.balance.Req7505HisBalQry;
import com.fingard.dsp.bank.reqrespobj.balance.Req7506BalQry;
import com.fingard.dsp.bank.reqrespobj.balance.RetAts7505HisBalQry;
import com.fingard.dsp.bank.reqrespobj.balance.RetAts7506BalQry;
import com.fingard.dsp.bank.reqrespobj.balance.detail.RetAtsBalDetail;
import com.fingard.dsp.bank.reqrespobj.balance.detail.RetAtsHisBalDetail;
import com.fingard.dsp.bank.reqrespobj.enumeration.ENDirectRight;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;
import org.springframework.stereotype.Component;

@Component("ICBC02Balance")
public class ICBC02Balance extends ICBC02Base implements IBalance {

    static AtomicInteger atomicInteger = new AtomicInteger(1);

    //单个余额查询和批量余额查询，统一采用流处理方式
    //1、循环调用Req7506BalQry.readRecord()读取一个请求明细，然后写入发银行的XML对象
    //2、发银行
    //3、循环调用XmlTextReader.read()读取一个银行返回节点，赋值返回ATS的明细对象，
    //   然后调用RetAts7506BalQry.writeRetDetail()，写入返回ATS的明细
    public RetAts7506BalQry d_7506_BalQry(Req7506BalQry p_req7506) throws Exception {//余额查询
        RetAts7506BalQry retAts = new RetAts7506BalQry(p_req7506.reqHeader);
        retAts.writeStart();//写返回ATS的统一头部信息
        WriteBankLogLn("进入余额查询处理类 ");
        while (p_req7506.readRecord()) {
            if (p_req7506.readedDetail.directRight != null && p_req7506.readedDetail.directRight.contains(ENDirectRight.CASHPOOLS.getValue())) {
                d_7506_BalQry_CashPool(p_req7506, retAts);
            } else {
                d_7506_BalQry_NoCashPool(p_req7506, retAts);
            }
        }
        retAts.writeEnd();
        return retAts;
    }

    private void d_7506_BalQry_CashPool(Req7506BalQry p_req7506, RetAts7506BalQry retAts) throws Exception {
        try {
            bnkTransCode = "QFACCTMEAS";
            bnkPackageID = p_req7506.reqHeader.transSeqID;
            bnkfSeqno = bnkPackageID;
            bnkVersion = "0.0.1.0";
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            //写入ICBC02通用的头部节点
            writeCommonHeader(xmlWriter);
            xmlWriter.writeElementString("AccNo", p_req7506.readedDetail.actNum);
            xmlWriter.writeElementString("ReqReserved1", convertCurToBank(p_req7506.readedDetail.actCur));
            xmlWriter.writeElementString("ReqReserved2", "");
            xmlWriter.writeEndDocument();
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();

                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);

                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/CMS/eb/pub/RetCode");
                    if (isActiveRetCode(tmpRetCode)) {
                        RetAtsBalDetail tmpRetDetail = new RetAtsBalDetail();
                        tmpRetDetail.respCode = "0";
                        tmpRetDetail.actCur = convertCurToATS(tmpBkReader.getFirstTextNotNull("CurrType"));
                        tmpRetDetail.actNum = tmpBkReader.getFirstTextNotNull("AccNo");

                        String tmpUsableBalance = "";
                        if (tmpBkReader.getFirstText("ABanlance") != null) {
                            tmpUsableBalance = tmpBkReader.getFirstTextNotNull("ABanlance").trim();
                        }
                        if (tmpUsableBalance.length() > 0) {
                            tmpRetDetail.availBal = StringHelper.amountDivide100(tmpUsableBalance);
                        } else {
                            tmpRetDetail.availBal = "0.00";
                        }

                        String tmpBalance = "";
                        if (tmpBkReader.getFirstText("CBanlance") != null) {
                            tmpBalance = tmpBkReader.getFirstText("CBanlance").trim();
                        }
                        if (tmpBalance.length() > 0) {
                            tmpRetDetail.currBal = StringHelper.amountDivide100(tmpBalance);
                        } else {
                            tmpRetDetail.currBal = tmpRetDetail.availBal;
                        }
                        String tmpUsableCashBalance = "";
                        if (tmpBkReader.getFirstText("SumAvaAmt") != null) {
                            tmpUsableCashBalance = tmpBkReader.getFirstText("CBanlance").trim();
                        }
                        if (tmpUsableCashBalance.length() > 0) {
                            tmpRetDetail.cashPoolAvailBal = StringHelper.amountDivide100(tmpUsableCashBalance);
                        } else {
                            tmpRetDetail.cashPoolAvailBal = "0.00";
                        }
                        tmpRetDetail.cashPoolBal = tmpRetDetail.cashPoolAvailBal;
                        retAts.writeRetDetail(tmpRetDetail, p_req7506.isBatch);
                    } else {
                        retAts.writeRespCode("-1");
                        if (tmpBkReader.getSimpleText("iRetMsg") != null && tmpBkReader.getSimpleText("iRetMsg").length() > 0) {
                            retAts.writeRespInfo(tmpBkReader.getSimpleText("iRetMsg"));
                        } else {
                            retAts.writeRespInfo(tmpBkReader.getSimpleText("RetMsg"));
                        }
                    }
                } else {
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo(tmpSbMsg.toString());
                }
            } else {
                retAts.writeRespCode("-1");
                retAts.writeRespInfo(tmpStrRet[1]);
            }
        } catch (Exception e) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(e.getMessage());
            e.printStackTrace();
            WriteBankLogLn("交易失败：发送异常" + e);
        }
    }

    public void d_7506_BalQry_NoCashPool(Req7506BalQry p_req7506, RetAts7506BalQry retAts) throws Exception {
        try {
            String savingType = p_req7506.savingType;
            //保证金账户
            if (savingType != null && savingType.equals("3")) {
                bnkTransCode = "QBAILINF";
            } else {
                bnkTransCode = "QACCBAL";
            }
            bnkPackageID = p_req7506.reqHeader.transSeqID;
            bnkfSeqno = bnkPackageID;
            bnkVersion = "0.0.1.0";
            String nextTag = "ture";
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            //写入ICBC02通用的头部节点
            writeCommonHeader(xmlWriter);
            if (bnkTransCode.equals("QACCBAL")) {
                xmlWriter.writeElementString("TotalNum", String.valueOf(p_req7506.detailCount));
                xmlWriter.writeElementString("BLFlag", "0");
                xmlWriter.writeElementString("SynFlag", StringHelper.hasAnyChar(p_req7506.readedDetail.swiftCode) ? "0" : "1");
                boolean isSubAct = p_req7506.readedDetail.higherLevelAct.length() > 0;
                xmlWriter.writeStartElement("rd");
                xmlWriter.writeElementString("iSeqno", String.valueOf(1));
                xmlWriter.writeElementString("AccNo", isSubAct ? p_req7506.readedDetail.higherLevelAct : p_req7506.readedDetail.actNum);
                xmlWriter.writeElementString("CurrType", convertCurToBank(p_req7506.readedDetail.actCur));
                xmlWriter.writeElementClosed("ReqReserved3");
                xmlWriter.writeElementString("AcctSeq", isSubAct ? p_req7506.readedDetail.actNum : "");
                xmlWriter.writeEndElement();
            } else {
                xmlWriter.writeElementString("AccNo", p_req7506.readedDetail.actNum);
                xmlWriter.writeElementString("CurrType", convertCurToBank(p_req7506.readedDetail.actCur));
                xmlWriter.writeElementString("NextTag", nextTag);
            }
            xmlWriter.writeEndDocument();
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();

                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);

                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/CMS/eb/pub/RetCode");
                    if (isActiveRetCode(tmpRetCode)) {
                        nextTag = tmpBkReader.getFirstText("/CMS/eb/out/NextTag");
                        while (tmpBkReader.read("/CMS/eb/out/rd")) {
                            RetAtsBalDetail tmpRetDetail = new RetAtsBalDetail();
                            if (bnkTransCode.equals("QBAILINF")) {
                                tmpRetDetail.respCode = "0";
                                tmpRetDetail.actCur = convertCurToATS(tmpBkReader.readedXElement.getSingleText("CurrType"));
                                tmpRetDetail.actNum = tmpBkReader.readedXElement.getSingleText("AccNo");

                                String tmpUsableBalance = "";
                                if (tmpBkReader.readedXElement.getSingleText("UsableBalance") != null) {
                                    tmpUsableBalance = tmpBkReader.readedXElement.getSingleText("UsableBalance").trim();
                                }
                                if (tmpUsableBalance.length() > 0) {
                                    tmpRetDetail.availBal = StringHelper.amountDivide100(tmpUsableBalance);
                                } else {
                                    tmpRetDetail.availBal = "0.00";
                                }

                                String tmpBalance = "";
                                if (tmpBkReader.readedXElement.getSingleText("Balance") != null) {
                                    tmpBalance = tmpBkReader.readedXElement.getSingleText("Balance").trim();
                                }
                                if (tmpBalance.length() > 0) {
                                    tmpRetDetail.currBal = StringHelper.amountDivide100(tmpBalance);
                                } else {
                                    tmpRetDetail.currBal = tmpRetDetail.availBal;
                                }
                                tmpRetDetail.actCur = tmpBkReader.readedXElement.getSingleText("CurrType");
                            } else if (tmpBkReader.readedXElement.getSingleText("iRetCode").equals("0")) {
                                tmpRetDetail.respCode = "0";
                                tmpRetDetail.actCur = convertCurToATS(tmpBkReader.readedXElement.getSingleText("CurrType"));
                                tmpRetDetail.actNum = tmpBkReader.readedXElement.getSingleText("AccNo");

                                String tmpUsableBalance = "";
                                if (tmpBkReader.readedXElement.getSingleText("UsableBalance") != null) {
                                    tmpUsableBalance = tmpBkReader.readedXElement.getSingleText("UsableBalance").trim();
                                }
                                if (tmpUsableBalance.length() > 0) {
                                    tmpRetDetail.availBal = StringHelper.amountDivide100(tmpUsableBalance);
                                } else {
                                    tmpRetDetail.availBal = "0.00";
                                }

                                String tmpBalance = "";
                                if (tmpBkReader.readedXElement.getSingleText("Balance") != null) {
                                    tmpBalance = tmpBkReader.readedXElement.getSingleText("Balance").trim();
                                }
                                if (tmpBalance.length() > 0) {
                                    tmpRetDetail.currBal = StringHelper.amountDivide100(tmpBalance);
                                } else {
                                    tmpRetDetail.currBal = tmpRetDetail.availBal;
                                }
                            } else {
                                tmpRetDetail.respCode = "-1";
                                tmpRetDetail.respInfo = tmpBkReader.readedXElement.getSingleText("iRetMsg");
                            }
                            retAts.writeRetDetail(tmpRetDetail, p_req7506.isBatch);
                        }
                    } else {
                        retAts.writeRespCode("-1");
                        if (tmpBkReader.getSimpleText("iRetMsg") != null && tmpBkReader.getSimpleText("iRetMsg").length() > 0) {
                            retAts.writeRespInfo(tmpBkReader.getSimpleText("iRetMsg"));
                        } else {
                            retAts.writeRespInfo(tmpBkReader.getSimpleText("RetMsg"));
                        }
                    }
                } else {
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo(tmpSbMsg.toString());
                }
            } else {
                retAts.writeRespCode("-1");
                retAts.writeRespInfo(tmpStrRet[1]);
            }
        } catch (Exception e) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(e.getMessage());
            e.printStackTrace();
            WriteBankLogLn("交易失败：发送异常" + e);
        }
    }

    @Override
    public RetAts7505HisBalQry d_7505_BalQry(Req7505HisBalQry p_req7505) throws Exception {
        RetAts7505HisBalQry retAts = new RetAts7505HisBalQry(p_req7505.reqHeader);
        String tmpRespCode = "";
        String tmpRespInfo = "";
        retAts.writeStart();//写返回ATS的统一头部信息
        try {
            bnkPackageID = p_req7505.reqHeader.transSeqID;
            bnkTransCode = "QHISBAL";
            bnkfSeqno = bnkPackageID;
            bnkVersion = "0.0.1.0";
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            //写入ICBC02通用的头部节点
            writeCommonHeader(xmlWriter);
            xmlWriter.writeElementString("AccNo", p_req7505.actNum);
            xmlWriter.writeElementString("CurrType", convertCurToBank(p_req7505.actCur));
            xmlWriter.writeElementString("BeginDate", p_req7505.dateFrom);
            xmlWriter.writeElementString("EndDate", p_req7505.dateTo);
            xmlWriter.writeElementClosed("ReqReserved1");
            xmlWriter.writeElementClosed("ReqReserved2");
            xmlWriter.writeEndDocument();
            String[] tmpRetBkStr = sendToBank(xmlWriter.toXmlString());
            if (tmpRetBkStr[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetBkStr[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/CMS/eb/pub/RetCode");
                    String tmpRetMsg = tmpBkReader.getFirstText("/CMS/eb/pub/RetMsg");
                    if (isActiveRetCode(tmpRetCode)) {
                        while (tmpBkReader.read("/CMS/eb/out/rd")) {
                            RetAtsHisBalDetail tmpRetDetail = new RetAtsHisBalDetail();
                            String tmpETYDAT = tmpBkReader.readedXElement.getSingleText("Date");
                            if (tmpETYDAT.length() == 8) {
                                tmpRetDetail.balDate = tmpETYDAT.substring(0, 4) + "-" + tmpETYDAT.substring(4, 6) + "-" + tmpETYDAT.substring(6, 8);
                            } else {
                                tmpRetDetail.balDate = tmpETYDAT;
                            }
                            tmpRetDetail.actBal = StringHelper.amountDivide100(tmpBkReader.readedXElement.getSingleText("Amount"));
                            retAts.writeRetDetail(tmpRetDetail);
                        }
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpRetMsg;
                    }
                } else {
                    tmpRespCode = "-1";
                    tmpRespInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRespCode = "-1";
                tmpRespInfo = tmpRetBkStr[1];
            }

        } catch (Exception e) {
            tmpRespCode = "-1";
            tmpRespInfo = e.getMessage();
            e.printStackTrace();
        }
        if (tmpRespCode.equals("-1")) {
            retAts = new RetAts7505HisBalQry(p_req7505.reqHeader);
            retAts.writeStart();//写返回ATS的统一头部信息
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("返回结果为空，所查询时间段内不存在历史余额");
        }
        retAts.writeEnd();
        return retAts;
    }

}
